package cn.com.hori.cms.service.impl;

import cn.com.hori.cms.entities.Manager;
import cn.com.hori.cms.service.ManagerService;
import cn.com.hori.cms.dao.ManagerRepository;
import cn.com.hori.cms.dao.TokenRepository;
import cn.com.hori.cms.entities.AdminToken;
import cn.com.hori.cms.model.LoginInfo;
import cn.com.hori.cms.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 刘艺
 * @date 2018/3/8 15:37
 */
@Service
public class ManagerServiceImpl implements ManagerService {
    private static Logger logger = LoggerFactory.getLogger(ManagerServiceImpl.class);


    /**
     * 管理员的数据源
     */
    @Autowired
    private ManagerRepository managerRepository;

    /**
     * token 的数据源
     */
    @Autowired
    private TokenRepository tokenRepository;

    /**
     * 登录验证
     * 登录成功 返回 AdminToken 有效对象
     * 登录失败 返回 null
     *
     * @return AdminToken对象
     */
    @Override
    public AdminToken loginSubmit(LoginInfo loginInfo) {
        logger.debug("登录的管理员的输入为{}", loginInfo);

        if (loginInfo == null) {
            return null;
        }

        Manager manager = managerRepository.findManagerByManagerId(loginInfo.getUsername());
        if (manager == null) {
            return null;
        }
        String password = manager.getPassword();

        boolean isPassword = password.equals(MD5Util.getMD5String(loginInfo.getPassword()));
        logger.debug("密码是否相同{}", isPassword);

        if (isPassword) {

            AdminToken adminToken = tokenRepository.save(new AdminToken(manager.getManagerId(), manager.getManagerName()));
            logger.debug("登录的token为：" + adminToken);
            return adminToken;
        } else {
            return null;
        }
    }
}
